package cn.itcast.bos.web.action.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.JoinType;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import oracle.net.aso.a;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;

import cn.itcast.bos.domain.base.Area;
import cn.itcast.bos.domain.base.FixedArea;
import cn.itcast.bos.domain.base.SubArea;
import cn.itcast.bos.service.base.AreaService;
import cn.itcast.bos.service.base.FixedAreaService;
import cn.itcast.bos.service.base.SubAreaService;
import cn.itcast.bos.web.action.common.BaseAction;

@Namespace("/")
@ParentPackage("json-default")
@Controller
@Scope("prototype")
public class SubAreaAction extends BaseAction<SubArea> {

	@Autowired
	private SubAreaService subAreaService;

	// 接收上传文件
	private File file;

	public void setFile(File file) {
		this.file = file;
	}

	@Autowired
	private AreaService areaService;
	@Autowired
	private FixedAreaService fixedAreaService;

	// 文件的意见上传
	@Action(value = "subArea_batchImport")
	public String subAreaBatchImport() throws IOException {
		// xls/xlsx表格里的数据一行就是一个对象，用一个集合容器，装对象
		List<SubArea> subAreas = new ArrayList<SubArea>();
		// 加载解析对象
		HSSFWorkbook hssfWorkbook = new HSSFWorkbook(new FileInputStream(file));
		// 获取一个sheet,第一个
		HSSFSheet sheetAt = hssfWorkbook.getSheetAt(0);
		// 获得里面的每一行数据对象
		for (Row row : sheetAt) {
			// 去掉表头
			if (row.getRowNum() == 0) {
				continue;
			}
			// 去掉空行
			if (row.getCell(0) == null) {
				continue;
			}
			SubArea subArea = new SubArea();
			// 分区编号
			subArea.setId(row.getCell(0).getStringCellValue());
			// 定区编码
			FixedArea fixedArea = fixedAreaService.findFixedAreaById(row
					.getCell(1).getStringCellValue());
			subArea.setFixedArea(fixedArea);
			// 区域编码,查询区域进行添加
			Area area = areaService.findAreaById(row.getCell(2)
					.getStringCellValue());
			subArea.setArea(area);
			// 关键字
			subArea.setKeyWords(row.getCell(3).getStringCellValue());
			// 启示号
			subArea.setStartNum(row.getCell(4).getStringCellValue());
			// 结束号
			subArea.setEndNum(row.getCell(5).getStringCellValue());
			// 单双号
			subArea.setSingle(row.getCell(6).getStringCellValue().charAt(0));
			// 位置信息
			subArea.setAssistKeyWords(row.getCell(7).getStringCellValue());

			subAreas.add(subArea);

		}
		// 调用业务层进行储存
		subAreaService.saveBatch(subAreas);
		return NONE;
	}
	

	//数据的分页查询
	@Action(value="subArea_findPageQuery",results={@Result(name="success",type="json")})
	public String findPageQuery() {
		System.err.println("cccccccccccccccccccccccccccc");	
		Specification<SubArea> specification=new Specification<SubArea>() {
			
			@Override
			public Predicate toPredicate(Root<SubArea> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				//List<Predicate> predicates=new ArrayList<Predicate>();
				Predicate predicate = cb.conjunction();
				Join<SubArea, Area> areaJoin=root.join("area",JoinType.INNER);
				if (model.getArea()!=null) {
					System.err.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
					//省 String province 	
					if (StringUtils.isNotBlank(model.getArea().getProvince())) {
						System.err.println("bbbbbbbbbbbbbbbbbbbbbbbbbbbbbb----------------"+model.getArea().getProvince());
						predicate = cb.and(predicate,cb.like(areaJoin.get("province").as(String.class), "%"+model.getArea().getProvince()+"%"));
					}
					//市String city
					if (StringUtils.isNotBlank(model.getArea().getCity())) {
					    predicate = cb.and(predicate,cb.like(areaJoin.get("city").as(String.class), "%"+model.getArea().getCity()+"%"));
					}
					//区
					if (StringUtils.isNotBlank(model.getArea().getDistrict())) {
						predicate = cb.and(predicate,cb.like(areaJoin.get("district").as(String.class), "%"+model.getArea().getDistrict()+"%"));
					}
				}
				//定区编码
				Join<SubArea, FixedArea> fixedAreaJoin=root.join("fixedArea",JoinType.INNER);
				if (model.getFixedArea()!=null&&StringUtils.isNotBlank(model.getFixedArea().getId())) {
					predicate=cb.and(predicate,cb.equal(fixedAreaJoin.get("id").as(String.class),model.getFixedArea().getId()));
				}
				//关键字String keyWords
				if (StringUtils.isNotBlank(model.getKeyWords())) {
					predicate=cb.and(predicate,cb.like(root.get("keyWords").as(String.class), "%"+model.getKeyWords()+"%"));
				}
				
				return predicate;
			}
		};
		
		Pageable pageable=new PageRequest(page-1, rows);
		Page<SubArea> subAreaPage=subAreaService.findPageQuery(specification,pageable);
		pushPageDataToValueStack(subAreaPage);
		return SUCCESS;
	}
	
	//新增数据
	@Action(value="subArea_save",results={@Result(name="success",type="redirect",location="./pages/base/sub_area.html")})
	public String save() {
		
		subAreaService.save(model);
		return SUCCESS;
	}
	
	private String ids;
	
	public void setIds(String ids) {
		this.ids = ids;
	}

	//分区的作废
	@Action(value="subArea_deltag",results={@Result(name="success",type="redirect",location="./pages/base/sub_area.html")})
	public String subAreaDeltag() {
		subAreaService.subAreaDeltag(ids);
		return SUCCESS;
	}
	
	//分区的还原
	@Action(value="subArea_backtag",results={@Result(name="success",type="redirect",location="./pages/base/sub_area.html")})
	public String subAreaBacktag() {
		subAreaService.subAreaBacktag(ids);
		return SUCCESS;
	}
	
	//关联定区的分区查询
	@Action(value="subArea_associationFixedArea",results={@Result(name="success",type="json")})
	public String subAreaAssociationFixedArea() {
		Specification<SubArea> specification=new Specification<SubArea>() {
			@Override
			public Predicate toPredicate(Root<SubArea> root,
					CriteriaQuery<?> query, CriteriaBuilder cb) {
				Predicate predicate=null;
				Join<SubArea, FixedArea> fixedAreaJoin=root.join("fixedArea",JoinType.INNER);
				if (model.getFixedArea()!=null&&StringUtils.isNotBlank(model.getFixedArea().getId())) {
					predicate=cb.and(cb.equal(fixedAreaJoin.get("id").as(String.class),model.getFixedArea().getId()));
				}
				return predicate;
			}
		};
		List<SubArea> subAreas=subAreaService.subAreaAssociationFixedArea(specification);
		
		ActionContext.getContext().getValueStack().push(subAreas);
		return SUCCESS;
	}
	
}
